<template>
    <div class="app-container">
      <el-card class="box-card">
      <div slot="header" class="clearfix">
            <span>Word模板管理</span>
        <el-button style="float: right; padding: 3px 0" link @click="goBack">返回</el-button>
        </div>
  
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form :model="templateInfo" label-width="100px" size="small">
            <el-form-item label="模板名称">
              <el-input v-model="templateInfo.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="模板类型">
              <el-input v-model="templateInfo.type" disabled></el-input>
            </el-form-item>
            <el-form-item label="版本号">
              <el-input v-model="templateInfo.version" disabled></el-input>
            </el-form-item>
            <el-form-item label="最近更新">
              <el-input v-model="updateTimeDisplay" disabled></el-input>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      
      <el-divider content-position="center">模板操作</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="24" class="mb20">
          <el-button-group>
            <el-button type="primary" icon="el-icon-upload2" @click="handleUpload">上传新版本</el-button>
            <el-button type="success" icon="el-icon-download" @click="handleDownload">下载模板</el-button>
            <el-button type="info" icon="el-icon-view" @click="handlePreview">预览模板</el-button>
            <el-button type="warning" icon="el-icon-edit" @click="goToEditor">在线编辑</el-button>
          </el-button-group>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <el-divider content-position="center">变量列表</el-divider>
          <el-table :data="variableList" size="small" border style="width: 100%">
            <el-table-column prop="name" label="变量名" width="180"></el-table-column>
            <el-table-column prop="description" label="描述"></el-table-column>
            <el-table-column prop="defaultValue" label="默认值" width="180"></el-table-column>
          </el-table>
        </el-col>
      </el-row>
      </el-card>
  
    <!-- 文件上传对话框 -->
    <el-dialog title="上传新版本" :visible.sync="uploadDialog.visible" width="500px" append-to-body>
        <el-upload
        class="upload-template"
        ref="upload"
        :action="uploadDialog.action"
        :headers="uploadDialog.headers"
        :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
        :auto-upload="false"
        :limit="1"
        :file-list="uploadDialog.fileList"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传word文档(docx)，且不超过10MB</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">确 定</el-button>
        <el-button @click="cancelUpload">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 预览对话框 -->
    <el-dialog title="模板预览" :visible.sync="previewDialog.visible" width="80%" append-to-body>
      <div class="preview-container" v-loading="previewDialog.loading">
        <div v-html="previewDialog.content"></div>
            </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewDialog.visible = false">关闭</el-button>
          </div>
      </el-dialog>
    </div>
  </template>
  
<script>
import { getTemplate, previewTemplate, listTemplateVariables, getWordContent, saveWordContent } from "@/api/qep/certificate/template";
import { getToken } from "@/utils/auth";
import { parseTime } from "@/utils/ruoyi";

export default {
  name: "WordManager",
  data() {
    return {
      // 模板ID
      templateId: null,
      // 模板信息
      templateInfo: {
        id: null,
        name: '',
        type: '',
        version: 1,
        templateFormat: 'DOCX',
        updateTime: null
      },
      // 变量列表
      variableList: [],
      // 上传对话框
      uploadDialog: {
        visible: false,
        action: "/dev-api/qep/certificate/template/upload",
        headers: { Authorization: "Bearer " + getToken() },
        fileList: []
      },
      // 预览对话框
      previewDialog: {
        visible: false,
        loading: false,
        content: ''
      }
    };
  },
  computed: {
    updateTimeDisplay() {
      return this.templateInfo.updateTime ? parseTime(this.templateInfo.updateTime) : '';
    }
  },
  created() {
    // 从路由获取模板ID
    this.templateId = this.$route.query.id;
    if (this.templateId) {
      this.getTemplateInfo();
      this.getVariableList();
    } else {
      this.$modal.msgError("未指定模板ID");
      this.goBack();
    }
  },
  methods: {
    // 获取模板信息
    getTemplateInfo() {
      getTemplate(this.templateId).then(response => {
        this.templateInfo = response.data;
      }).catch(() => {
        this.$modal.msgError("获取模板信息失败");
      });
    },
    
    // 获取变量列表
    getVariableList() {
      listTemplateVariables(this.templateId).then(response => {
        this.variableList = response.data || [];
      }).catch(() => {
        this.$modal.msgError("获取变量列表失败");
      });
    },
    
    // 上传按钮
    handleUpload() {
      this.uploadDialog.fileList = [];
      this.uploadDialog.visible = true;
    },
    
    // 文件上传前处理
    beforeUpload(file) {
      // 验证文件类型
    const isDocx = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
    if (!isDocx) {
        this.$modal.msgError("上传文件只能是docx格式!");
        return false;
    }
      // 验证文件大小
      const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
        this.$modal.msgError("上传文件大小不能超过10MB!");
        return false;
      }
      return true;
    },
    
    // 提交上传
    submitUpload() {
      if (this.$refs.upload.uploadFiles.length === 0) {
        this.$modal.msgError("请选择要上传的文件");
        return;
      }
      
      // 准备上传数据
      const file = this.$refs.upload.uploadFiles[0].raw;
      const formData = new FormData();
      formData.append('file', file);
      formData.append('name', this.templateInfo.name);
      formData.append('type', this.templateInfo.type);
      
      // 使用自定义上传而不是el-upload的自动上传
      let loading = this.$loading({
        lock: true,
        text: '正在上传...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 发起上传请求
      const xhr = new XMLHttpRequest();
      xhr.open('POST', this.uploadDialog.action, true);
      
      // 设置请求头
      xhr.setRequestHeader('Authorization', this.uploadDialog.headers.Authorization);
      
      xhr.onload = () => {
        loading.close();
        if (xhr.status === 200) {
          try {
            const response = JSON.parse(xhr.responseText);
            if (response.code === 200) {
              this.uploadDialog.visible = false;
              this.$modal.msgSuccess("上传成功");
              this.getTemplateInfo(); // 刷新模板信息
    } else {
              this.$modal.msgError("上传失败: " + response.msg);
            }
          } catch (e) {
            this.$modal.msgError("上传失败，响应解析错误");
          }
        } else {
          this.$modal.msgError("上传失败，状态码: " + xhr.status);
        }
      };
      
      xhr.onerror = () => {
        loading.close();
        this.$modal.msgError("上传失败，网络错误");
      };
      
      xhr.send(formData);
    },
    
    // 上传成功
    handleUploadSuccess(res) {
      this.uploadDialog.visible = false;
      if (res.code === 200) {
        this.$modal.msgSuccess("上传成功");
        this.getTemplateInfo(); // 刷新模板信息
      } else {
        this.$modal.msgError("上传失败：" + res.msg);
      }
    },
    
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传失败");
    },
    
    // 取消上传
    cancelUpload() {
      this.uploadDialog.visible = false;
      this.$refs.upload.clearFiles();
    },
    
    // 下载模板
    handleDownload() {
      if (!this.templateInfo.id) return;
      
      previewTemplate(this.templateInfo.id).then(response => {
        const blob = new Blob([response], { 
          type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
        });
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = this.templateInfo.name + '.docx';
    link.click();
        window.URL.revokeObjectURL(link.href);
      }).catch(() => {
        this.$modal.msgError("下载失败");
      });
    },
    
    // 预览模板
    handlePreview() {
      if (!this.templateInfo.id) return;
      
      this.previewDialog.visible = true;
      this.previewDialog.loading = true;
      this.previewDialog.content = '';
      
      previewTemplate(this.templateInfo.id).then(response => {
        // 对于Word文档，只显示提示信息
        this.previewDialog.content = '<div style="text-align:center; padding: 20px;">' +
          '<p>Word文档无法直接在浏览器中预览，请使用下载功能下载后查看。</p>' +
          '</div>';
        this.previewDialog.loading = false;
      }).catch(() => {
        this.previewDialog.loading = false;
        this.$modal.msgError("预览失败");
      });
    },
    
    // 跳转到在线编辑器
    goToEditor() {
      this.$router.push({ 
        path: '/certificate/template/word-editor', 
        query: { id: this.templateId } 
      });
    },
    
    // 返回
    goBack() {
      this.$router.push({ path: '/certificate/template' });
    }
  }
};
  </script>
  
  <style scoped>
.app-container {
    padding: 20px;
  margin-top: 0;
}
.box-card {
  margin-top: 0;
  width: 100%;
}
.clearfix:after {
  content: "";
  display: table;
  clear: both;
}
.mb20 {
  margin-bottom: 20px;
}
.upload-template .el-upload {
  width: 100%;
}
.el-upload--text {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100%;
}
.el-upload--text:hover {
  border-color: #409eff !important;
}
.preview-container {
  min-height: 300px;
  border: 1px solid #dcdfe6;
    padding: 20px;
  background-color: #fff;
  }
  </style>